﻿using System;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using Eneta.Portal.Authentication.Live;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;
using Eneta.Portal.Common.Definitions;

namespace Eneta.Portal.Authentication.Pages
{
    public class RegisterPage : Page
    {
        protected TextBox displayNameField;
        protected Label lblDisplayNameError;
        protected TextBox emailField;
        protected Label lblEmailError;
        protected Button butSubmit;

        protected HtmlGenericControl warningBox;
        protected string redir;
        protected HtmlControl userBlock;
        protected HtmlControl passwordBlock;

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.butSubmit.Click += new EventHandler(Submit_Click);
        }
        #endregion
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            warningBox.Visible = false;
            redir = Request.QueryString["Source"];

            if (redir == null)
            {
                redir = SPContext.Current.Web.Url;
            }

            if (User.Identity.IsAuthenticated)
            {
                if (!IsPostBack)
                {
                    var nameParts = User.Identity.Name.Split('|');
                    var userName = nameParts[nameParts.Length - 1];
                    var bup = BlogUserProfile.GetUser(userName);

                    if (bup != null)
                    {
                        displayNameField.Text = bup.DisplayName;
                        emailField.Text = bup.Email;
                    }
                    else
                    {
                        Response.Redirect(redir);
                    }
                }
            }
            else
            {
                Response.Redirect(redir);
            }
        }

        public void Submit_Click(Object sender, EventArgs e)
        {
            

            if (string.IsNullOrEmpty(displayNameField.Text))
            {
                userBlock.Attributes["class"] = "info-row failed-info";
                lblDisplayNameError.Text = Resources.GetResourceString("UserNameIsMissing");
                lblDisplayNameError.Visible = true;
                warningBox.Visible = true;
                return;
            }
            if (!Regex.IsMatch(displayNameField.Text, "^[a-zA-Z0-9]{4,15}$"))
            {
                userBlock.Attributes["class"] = "info-row failed-info";
                lblDisplayNameError.Text = Resources.GetResourceString("UserNameIsInvalid");
                lblDisplayNameError.Visible = true;
                warningBox.Visible = true;
                return;
            }
            
            using (var site = new SPSite(SPContext.Current.Web.Site.ID))
            {
                using (var web = site.OpenWeb())
                {
                    var nameParts = User.Identity.Name.Split('|');
                    var userName = nameParts[nameParts.Length - 1];
                    var queryString = @"<Where><And><Eq><FieldRef Name=""Title"" /><Value Type=""Text"">{0}</Value></Eq>";
                    queryString += @"<Neq><FieldRef Name=""SysID"" /><Value Type=""Text"">{1}</Value></Neq></And></Where>";
                    queryString = string.Format(queryString, displayNameField.Text, userName);

                    var list = web.GetList(Lists.ProfileList);
                    var query = new SPQuery();
                    query.Query = queryString;

                    var results = list.GetItems(query);
                    if (results != null)
                        if (results.Count > 0)
                        {
                            userBlock.Attributes["class"] = "info-row failed-info";
                            lblDisplayNameError.Text = Resources.GetResourceString("UserNameIsAlreadyTaken");
                            lblDisplayNameError.Visible = true;
                            warningBox.Visible = true;
                            return;
                        }
                }
            }
            userBlock.Attributes["class"] = "info-row";

            if (string.IsNullOrEmpty(emailField.Text))
            {
                passwordBlock.Attributes["class"] = "info-row failed-info";
                lblEmailError.Text = Resources.GetResourceString("EmailIsMissing");
                lblEmailError.Visible = true;
                warningBox.Visible = true;
                return;
            }
            if (!Regex.IsMatch(emailField.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
            {
                passwordBlock.Attributes["class"] = "info-row failed-info";
                lblEmailError.Text = Resources.GetResourceString("EmailIsIncorrect");
                lblEmailError.Visible = true;
                warningBox.Visible = true;
                return;
            }

            if (!User.Identity.IsAuthenticated)
                return;

            var profileId = 0;

            try
            {
                var siteId = SPContext.Current.Site.ID;
                var sec = new SPSecurity.CodeToRunElevated(
                    delegate
                        {
                            var nameParts = User.Identity.Name.Split('|');
                            var userName = nameParts[nameParts.Length - 1];

                            var bup = BlogUserProfile.GetUser(userName);
                            bup.DisplayName = displayNameField.Text;
                            bup.Email = emailField.Text;
                            bup.Update();

                            profileId = bup.ItemId;
                            var name = User.Identity.Name;

                            using(var site = new SPSite(siteId))
                            using (var web = site.OpenWeb())
                            {
                                AddNewSpUser(web, name, emailField.Text, displayNameField.Text);

                                var userMail = emailField.Text;

                                try
                                {
                                    var profileLink = EnetaApplication.PortalProfilePageUrl + "?profileID=" + profileId;
                                    var mailer = new MailerService();
                                    var addresses = new[] { userMail, EnetaApplication.PortalModeratorEmail };

                                    mailer.SendMailByTemplate("WelcomeMessage", displayNameField.Text, displayNameField.Text, profileLink, addresses);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogWarning("Error sending e-mail");
                                    Logger.LogException(ex);
                                }

                                web.Close();
                            }
                        });
                SPSecurity.RunWithElevatedPrivileges(sec);
            }
            catch(Exception ex)
            {
                Logger.LogException(ex);
                Response.Write("VIGA");
                Response.Write(ex.ToString());
                return;
            }
            //Response.Redirect(Request.QueryString["Source"]
            Logger.LogInfo("RegisterPage.Submit_Click(): profile page URL = " + EnetaApplication.PortalProfilePageUrl);
            Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profileId + "&msg=joined", false);
        }
        private void AddNewSpUser(SPWeb web, string userName, string email, string name)
        {
            var site = web.Site;

            try
            {
                site.AllowUnsafeUpdates = true;
                web.AllowUnsafeUpdates = true;

                var removeId = 0;
                foreach (SPUser usr in web.SiteUsers)
                {
                    if (usr.LoginName == "i:" + userName)
                    {
                        removeId = usr.ID;
                        break;
                    }
                }

                if (removeId != 0)
                {
                    web.SiteUsers.RemoveByID(removeId);
                    web.Update();
                }

                web.SiteUsers.Add("i:"+userName, email, name, string.Empty);
                var user = web.SiteUsers["i:"+userName];
                user.Email = email;
                user.Name = name;
                user.Update();

                try
                {
                    web.RoleAssignments.Remove(user);
                    web.Update();
                }
                catch(Exception ex)
                {
                    Logger.LogException(ex);
                }

                var breaking = false;
                foreach (SPGroup grp in web.Groups)
                {
                    foreach (SPRole role in grp.Roles)
                        if (role.PermissionMask.ToString() == "138612801")
                        {
                            grp.AddUser(user);
                            grp.Update();
                            breaking = true;
                        }
                    if (breaking)
                        break;
                }
                            
                web.Update();
            }
            catch(Exception ex)
            {
                Logger.LogInfo("AddNewSpUser(): Common error occured during user adding process");
                Logger.LogException(ex);
            }
            web.AllowUnsafeUpdates = false;
            site.AllowUnsafeUpdates = false;
        }       
    }
}